package com.jiezuo.common.util;

import com.alibaba.fastjson.JSONObject;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.Date;
import java.util.Map;

/**
 * JWT
 * @author lcm
 */
public class JavaWebToken {

    private static Key getKeyInstance(String secretKey) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(secretKey);
        Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
        return signingKey;
    }

    public static String createJWT(String user_name, String password, String secretKey, long TTLMillis) {

        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        long nowMillis = SystemClock.now();
        Date now = new Date(nowMillis);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("user_name", user_name);
        jsonObject.put("password", password);

        //添加构成JWT的参数
        JwtBuilder builder = Jwts.builder().setHeaderParam("typ", "JWT")
                .setIssuedAt(now) //创建时间
                .setSubject(jsonObject.toString()) //主题，也差不多是个人的一些信息
                .signWith(signatureAlgorithm, getKeyInstance(secretKey)); //签名

        //添加Token过期时间
        if (TTLMillis > 0) {
            //过期时间
            long expMillis = nowMillis + TTLMillis;
            //现在是什么时间
            Date exp = new Date(expMillis);
            //系统时间之前的token都是不可以被承认的
            builder.setExpiration(exp).setNotBefore(now);
        }

        //生成JWT
        return builder.compact();
    }

    //解析Token，同时也能验证Token，当验证失败返回null
    public static Map<String, Object> parserJavaWebToken(String jwt, String secretKey) {
        Map<String, Object> jwtClaims =
                Jwts.parser().setSigningKey(getKeyInstance(secretKey)).parseClaimsJws(jwt).getBody();
        return jwtClaims;
    }

}
